import React, { Component } from 'react'
import { Text, View, Animated, StyleSheet, Image, TouchableHighlight, ToastAndroid } from 'react-native'
import Video from 'react-native-video'
import Slider from '@react-native-community/slider'
import { Button } from '@ant-design/react-native'
import { linear } from 'react-native/Libraries/Animated/Easing'
let dataUrl = "http://www.johnyu.cn:3000/albums"
let mp3Url = "http://www.johnyu.cn/mp3/"
import Global from '../qm_comp/Global'
export default class MusicPlay extends Component {
    state = {
        /**
         * 是否收藏该音乐
         */
        isLike: false,
        userId: 0,
        paused: true, musics: [], mIndex: 0, duration: 0, currentTime: 0, rotate: new
            Animated.Value(0)
    }
    rotateValue = 0
    componentDidMount() {
        var that = this
        if (Global.UInfo != undefined) {
            console.log(Global.UInfo.userId);
            this.setState({
                userId: Global.UInfo.userId
            })
            setTimeout(() => {
                fetch('https://www.annjong.com/bcumusic/api/Like/selectByUserIdAndMusicId?LikeMusicId=' + 2 + '&likeUserId=' + Global.UInfo.userId)
                    .then(res => res.json())
                    .then(res => {
                        console.log(res);
                        if (res.msg == '已收藏该音乐') {
                            that.setState({
                                isLike: true
                            })
                        }
                        else if (res.msg == '未收藏该音乐') {
                            that.setState({
                                isLike: false
                            })
                        }
                    })
            }, 100);
        }

        /**
         * 钩子里面写一个判断，如果根据用户id和对应歌曲id找得到 收藏字段 的话，就标志为已经收藏，
         * 点击事件都一样，判断逻辑在后端
         */
        fetch(dataUrl).then(resp => resp.json())
            .then(musics => this.setState({ musics }))
        this.state.rotate.addListener(({ value }) => this.rotateValue = value)


    }
    _likeIt = () => {
        if (Global.UInfo == undefined) {
            ToastAndroid.show('先登录才能收藏哟', 2)
        } else {
            fetch('https://www.annjong.com/bcumusic/api/Like/likeMusic?LikeMusicId=' + 2 + '&likeUserId=' + this.state.userId)
                .then(res => res.json())
                .then(res => {
                    console.log(res);
                    ToastAndroid.show(res.msg, 2)
                })
        }
        this.setState({
            isLike: !this.state.isLike
        })
        console.log(this.state.isLike);

    }
    _playOrPause = () => {
        let animatedFunction = Animated.loop(Animated.timing(this.state.rotate,

            { duration: 5000, toValue: this.rotateValue + 360, easing: linear, useNativeDriver: true }))
        this.state.paused ? animatedFunction.start() : animatedFunction.stop()
        this.setState(state => ({ paused: !state.paused }))
    }
    _load = ({ duration }) => this.setState({ duration })
    _progress = ({ currentTime }) => this.setState({ currentTime })
    _seek = value => {
        this.player.seek(value)
    }
    _end = () => {
        this.setState(state => ({ mIndex: ++state.mIndex % this.state.musics.length }))
    }
    render() {
        let { musics: mus, mIndex: minx } = this.state
        let style = {
            transform: [{
                rotate: this.state.rotate.interpolate({
                    inputRange: [0, 360], outputRange: ['0deg', '360deg']
                })
            }]
        }

        return (
            <View>
                <Video ref={ref => this.player = ref}
                    onEnd={this._end}
                    paused={this.state.paused} onLoad={this._load} onProgress={this._progress}
                    source={{ uri: mp3Url + mus[1]?.name + ".mp3" }} />
                <Text style={{ fontSize: 40, textAlign: 'center' }}>{mus[1]?.name}</Text>
                <Text style={{ fontSize: 20, textAlign: 'center' }}>{mus[1]?.singer.join(',')}
                </Text>
                <Animated.Image style={[style, { width: 300, height: 300, borderRadius: 150, alignSelf: 'center' }]} source=
                    {{ uri: mus[1]?.img }} />
                <View style={styles.likeIt}>
                    <View style={styles.white_box}></View>
                    <TouchableHighlight onPress={this._likeIt}>
                        {this.state.isLike == true ? (
                            <Image source={require('../images/like.png')}></Image>
                        ) : (
                            <Image source={require('../images/unlike.png')}></Image>
                        )}
                    </TouchableHighlight>
                </View>
                <Slider
                    onSlidingComplete={this._seek}
                    value={this.state.currentTime} maximumValue={this.state.duration} />
                <Button onPress={this._playOrPause}>{this.state.paused ? "播放" : "暂停"}</Button>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    likeIt: {
        width: '100%',
        height: 50,
        // backgroundColor:'white',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginBottom: 20
    },
    white_box: {
        width: 50,
        height: 50,
        // backgroundColor:'white'
    },
    like_box: {
        width: 50,
        height: 50,
        // backgroundColor:'red'
    }
})
